package com.example.run_game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class RunHistory extends Activity
{
	private TextView tempText;
	
    // XML node keys
    static final String KEY_RUN = "run"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_START = "start";
    static final String KEY_DISTANCE = "distance";
    static final String KEY_TIME = "time";
    
    ListView list;
    HistoryAdapter adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_run_history);
		//pruneStuff(); //Uncomment this to create your own Index XML for the run history.
		
		//tempText = (TextView)findViewById(R.id.tempRunDump);
		//System.out.println(tempText);
		
		ArrayList<HashMap<String, String>> historyList = new ArrayList<HashMap<String, String>>();
		 
        XMLParser parser = new XMLParser();
        FileInputStream f;
		StringBuffer indexXml = new StringBuffer("");
       
        try
		{
			f = openFileInput("RunHistory");
			int ch;
			while ((ch = f.read()) != -1)
			{
				indexXml.append((char)ch);
			}
			//DO PARSING XML THING
			Document doc = parser.getDomElement(indexXml.toString()); // getting DOM element
	        
			NodeList nl = doc.getElementsByTagName(KEY_RUN);
	        // looping through all song nodes &lt;song&gt;
	        for (int i = 0; i < nl.getLength(); i++) {
	            // creating new HashMap
	            HashMap<String, String> map = new HashMap<String, String>();
	            Element e = (Element) nl.item(i);
	            // adding each child node to HashMap key =&gt; value
	            map.put(KEY_ID, parser.getValue(e, KEY_ID));
	            map.put(KEY_START, parser.getValue(e, KEY_START));
	            map.put(KEY_DISTANCE, parser.getValue(e, KEY_DISTANCE));
	            map.put(KEY_TIME, parser.getValue(e, KEY_TIME));
	 
	            // adding HashList to ArrayList
	            historyList.add(map);
	        }
	        
	        list=(ListView)findViewById(R.id.run_list);
	        
	        // Getting adapter by passing xml data ArrayList
	        adapter=new HistoryAdapter(this, historyList);
	        list.setAdapter(adapter);
	 
	        // Click event for single list row
	        list.setOnItemClickListener(new OnItemClickListener() {
	 
	            @Override
	            public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
	            {
	            	Toast.makeText(parent.getContext(), "Loading run data", Toast.LENGTH_SHORT).show();
	            	String routeID = "";
	            	TextView idView = (TextView)view.findViewById(R.id.routeID);
	            	routeID = (idView.getText()).toString();
	            	System.out.println("routeID being viewed: " + routeID);
	            	Intent intent = new Intent(getBaseContext(), PostRunInformation.class);
					Bundle bundle = new Bundle();
					bundle.putString("path", routeID);
					intent.putExtras(bundle);
					startActivity(intent);	
	 
	            }
	        });
			//((TextView)findViewById (R.id.textView1)).setText(indexXml.toString());
		} catch (FileNotFoundException e)
		{
			// TODO Uncomment this to create your own Index XML for the run history.
			//createIndexXML(); //
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
        setupProgressBar();
        populateProfileBar();
	}

	private void pruneStuff()
	{

		File f = getFilesDir();
		ArrayList<String> tobedeleted = new ArrayList<String>();		
		String finalString = "";
		ArrayList<String> filenames = new ArrayList<String>();
		for (File fi : f.listFiles())
		{
			if (fi.getName().startsWith("route"))
				filenames.add(fi.getName());
		}
		for (String filename : filenames)
		{
			FileInputStream fis;
			if (!filename.startsWith("route"))
				continue;
			try
			{
				fis = openFileInput(filename);
				ArrayList<Location> route = XMLParser.parseXMLRoute(fis);
				if (route.size()<15)
					tobedeleted.add(filename);
				if (Utils.RouteDistance(route) < 200)
					tobedeleted.add(filename);				
					
			} catch (FileNotFoundException e)
			{
				e.printStackTrace();
			} catch (IOException e)
			{	
				e.printStackTrace();
			} catch (SAXException e)
			{
				tobedeleted.add(filename);
				e.printStackTrace();
			}
		}
		for (String s : tobedeleted)
			deleteFile(s);
		createIndexXML();
	}

	protected void setupProgressBar()
	{	       
		DbManager db = new DbManager(this);
		Player player = new Player(db);
		int percentage = player.getProgressBarPercentage();
		int lvl = player.getLevel();	 
				
		((ProgressBar)findViewById (R.id.progressBar)).setProgress(percentage);			
		((TextView)findViewById (R.id.level_lower_text)).setText(""+lvl);		
		((TextView)findViewById (R.id.level_upper_text)).setText(""+(lvl+1));
	}
	

	private void createIndexXML()
	{
		File f = getFilesDir();
		ArrayList<String> tobedeleted = new ArrayList<String>();		
		String finalString = "";
		ArrayList<String> filenames = new ArrayList<String>();
		for (File fi : f.listFiles())
		{
			if (fi.getName().startsWith("route"))
				filenames.add(fi.getName());
		}
		TreeMap<Long,String> timeSortedXML = new TreeMap<Long,String>();
		for (String filename : filenames)
		{
			FileInputStream fis;
			if (!filename.startsWith("route"))
				continue;
			try
			{
				fis = openFileInput(filename);
				ArrayList<Location> route = XMLParser.parseXMLRoute(fis);
				if (route.size() > 0)
				{
					DecimalFormat df = new DecimalFormat("#.##");
					finalString = "";
					finalString += "<run>\n";
					long startTime = route.get(0).getTime();
					long duration = route.get(route.size()-1).getTime() - route.get(0).getTime();
					finalString += "<id>"+filename+"</id>\n";
					finalString += "<start>"+startTime+"</start>\n";
					finalString += "<distance>"+df.format(Utils.RouteDistance(route)/1000)+"km</distance>\n";
					finalString += "<time>"+Utils.formatMilliTime(duration, false)+"</time>\n";
					finalString += "</run>\n\n";
					timeSortedXML.put(startTime, finalString);
				}
				else
					tobedeleted.add(filename);
				
					
			} catch (FileNotFoundException e)
			{
				e.printStackTrace();
			} catch (IOException e)
			{	
				e.printStackTrace();
			} catch (SAXException e)
			{
				tobedeleted.add(filename);
				e.printStackTrace();
			}
		}
		String result = "<history>\n";
		for (Entry<Long,String> e : timeSortedXML.entrySet())
		{
			System.out.println("writing "+e.getKey());
			result += e.getValue();
		}
		result += "</history>\n";
		writeToXML(result);
	}
	
	private void writeToXML(String xmlString)
    {
    	try {
    		deleteFile("RunHistory");
			FileOutputStream fos = openFileOutput("RunHistory",Context.MODE_APPEND);
			System.out.println(xmlString);
			fos.write(xmlString.getBytes());
			fos.close();
		} catch (IOException e) {
			Log.e("RunHistory.java", "ROUTE FILE COULD NOT BE ACCESSED\n");
			e.printStackTrace();
		}
    }

	private void populateProfileBar()
	{
		DbManager db = new DbManager(this);
		Player mPlayer = new Player(db);
		ImageView profilePic = (ImageView)findViewById(R.id.list_image);
		Bitmap picture = mPlayer.getPicture();
		if(picture != null)
			profilePic.setImageBitmap(picture);
		DecimalFormat df = new DecimalFormat("#.##");

		TextView playerName = (TextView)findViewById(R.id.title);
		playerName.setText(mPlayer.getName().toString());
		TextView distTime = (TextView)findViewById(R.id.distance);
		distTime.setText("Total Dist/Time: "+df.format(mPlayer.getTotalDistance()/1000)+"km/"+ Utils.formatMilliTime(mPlayer.getTotalTime(),false));
		TextView avSpeed = (TextView)findViewById(R.id.average_speed);
		avSpeed.setText("Average Speed: "+df.format(mPlayer.getAvSpeed()*60*60/1000)+" kph");
		TextView calories = (TextView)findViewById(R.id.calories);
		calories.setText("Calories Burned: "+Integer.toString(mPlayer.getTotalCaloriesBurned()));
	}
}
